<template>
  <view class="page-wrapper">
    <!-- 可滚动内容（店铺信息、服务、评价等） -->
    <scroll-view class="scroll-content" scroll-y="true">
      <!-- 店铺 Banner -->
      <image class="shop-banner" :src="shopInfo.bannerImage || '/static/car_wash/1.png'" mode="widthFix"></image>
      
      <!-- 店铺信息 -->
      <view class="shop-info">
        <view class="shop-name">{{ shopInfo.name || '车百事汽车生活馆' }}</view>
        <view class="shop-rating">
          <view class="stars">
            <uni-icons type="star-filled" color="#FFCC33" v-for="n in Math.floor(shopInfo.rating || 4)" :key="n"></uni-icons>
            <uni-icons type="star" color="#E0E0E0" v-if="shopInfo.rating < 5"></uni-icons>
          </view>
          <text class="rating-text">{{ shopInfo.rating || 4.0 }}分</text>
          <text class="sales-text">销量：{{ shopInfo.sales || 356 }}</text>
        </view>
        <view class="shop-details">
          <view class="detail-item">
            <uni-icons type="clock" color="#666" size="16"></uni-icons>
            <text>营业时间：{{ shopInfo.businessHours || '周一至周五 早上8:00-晚上22:00' }}</text>
          </view>
          <view class="detail-item location-item" @click="goToNavigation">
            <uni-icons type="location" color="#666" size="16"></uni-icons>
            <text>{{ shopInfo.address || '山阳区人民路与解放路口' }}</text>
            <uni-icons type="right" color="#999" size="14"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 团购样式的服务项目区域 -->
      <view class="group-buy-section">
        <!-- 顶部标签栏 -->
        <view class="tabs">
          <view 
            class="tab-item" 
            :class="{'active': currentTab === 'all'}" 
            @click="switchTab('all')"
          >全部</view>
          <view 
            class="tab-item" 
            :class="{'active': currentTab === 'maintain'}" 
            @click="switchTab('maintain')"
          >保养</view>
          <view 
            class="tab-item" 
            :class="{'active': currentTab === 'repair'}" 
            @click="switchTab('repair')"
          >维修</view>
          <view 
            class="tab-item" 
            :class="{'active': currentTab === 'parts'}" 
            @click="switchTab('parts')"
          >配件</view>
          <view 
            class="tab-item" 
            :class="{'active': currentTab === 'other'}" 
            @click="switchTab('other')"
          >其他</view>
        </view>
      
        <!-- 团购列表 -->
        <view class="group-buy-list">
          <view 
            class="group-buy-item" 
            v-for="(item, index) in groupBuyList" 
            :key="index"
            @click="selectItem(item)"
          >
            <image class="item-image" :src="item.image" mode="aspectFill"></image>
            <view class="item-content">
              <view class="item-title">{{ item.title }}</view>
              <view class="item-desc" v-if="item.desc">{{ item.desc }}</view>
              <view class="item-price">
                <text class="current-price">¥{{ item.currentPrice }}</text>
                <text class="original-price">¥{{ item.originalPrice }}</text>
              </view>
              <view class="item-tags">
                <text class="tag">{{ item.tag }}</text>
                <text class="sales">共售{{ item.sales }}+</text>
              </view>
            </view>
            <button class="buy-btn" @click.stop="buyItem(item)">抢购</button>
          </view>
          <view class="more-group-buy" v-if="hasMore" @click="loadMore">
            <text>查看更多26个团购</text>
            <uni-icons type="right" color="#999" size="14"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 服务评价 -->
      <view class="review-section">
        <view class="section-title">服务评价</view>
        <view class="review-list">
          <view class="review-item" v-for="(item, index) in reviews" :key="index">
            <image class="review-avatar" :src="item.avatar" mode="aspectFill"></image>
            <view class="review-content">
              <view class="review-header">
                <text class="review-name">{{ item.name }}</text>
                <view class="review-stars">
                  <uni-icons type="star-filled" color="#FFCC33" v-for="(star, starIndex) in item.stars" :key="starIndex"></uni-icons>
                </view>
                <text class="review-date">{{ item.date }}</text>
              </view>
              <view class="review-text">{{ item.text }}</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="contact-area" @click="showContactModal">
        <image class="contact-icon" src="/static/car_wash/客服@2x.png" mode="aspectFit"></image>
        <text class="contact-text">联系客服</text>
      </view>
    </view>

    <!-- 底部弹出层 -->
    <view class="contact-modal" v-show="isShowContact">
      <view class="modal-mask" @click="closeModal"></view>
      <view class="modal-content">
        <view class="phone-number">{{ shopInfo.phone || '18642589456' }}</view>
        <view class="divider"></view>
        <button class="copy-btn" @click="copyPhone">复制</button>
        <view class="divider"></view>
        <button class="cancel-btn" @click="closeModal">取消</button>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js'

export default {
  data() {
    return {
      shopId: '1', // 默认店铺ID为1
      loading: false,
      shopInfo: {}, // 店铺信息
      reviews: [
        {
          avatar: "/static/car_wash/avatar.png", 
          name: "黄**",
          date: "2022.12.31",
          stars: 5,
          text: "洗的非常干净，几个小伙子很用心，态度也很好，强烈推荐来这家店洗车！！！"
        },
        {
          avatar: "/static/car_wash/avatar.png",
          name: "李**",
          date: "2022.12.30",
          stars: 5,
          text: "服务态度很好，洗车很专业，价格也合理，下次还会再来。"
        },
        {
          avatar: "/static/car_wash/avatar.png",
          name: "王**",
          date: "2022.12.29",
          stars: 4,
          text: "整体不错，就是等待时间有点长，不过洗得很干净。"
        }
      ],
      isShowContact: false,
      customerPhone: "18642589456",
      currentTab: 'all',
      
      // 动态数据
      serviceTypes: [], // 服务类型列表
      groupBuyList: [], // 当前显示的服务列表
      hasMore: true
    };
  },
  
  onLoad(options) {
    console.log('接收到的参数:', options);
    if (options.shopId) {
      this.shopId = options.shopId;
    }
    this.loadShopData();
  },
  
  methods: {
    // 加载店铺数据
    async loadShopData() {
      if (!this.shopId) return;
      
      this.loading = true;
      try {
        // 并行获取店铺信息和服务类型
        const [shopRes, typeRes] = await Promise.all([
          this.getShopInfoById(this.shopId), // 获取店铺信息
          this.getServiceTypesByShopId(this.shopId) // 获取服务类型
        ]);
        
        // 1. 处理店铺信息
        console.log('店铺信息接口响应:', shopRes);
        if (shopRes.code === 200) {
          this.shopInfo = shopRes.data || {};
          this.customerPhone = this.shopInfo.phone || "18642589456";
          console.log('处理后的店铺信息:', this.shopInfo);
        } else {
          console.log('获取店铺信息失败:', shopRes);
        }
        
        // 2. 处理服务类型
        console.log('服务类型接口响应:', typeRes);
        if (typeRes.code === 200) {
          this.serviceTypes = [
            { 
              key: 'all', 
              name: '全部', 
              typeId: null, 
              serviceCount: 0 
            },
            ...typeRes.data.map(type => ({
              key: this.getTypeKey(type.name),
              name: type.name,
              typeId: type.id,
              serviceCount: 0
            }))
          ];
          console.log('处理后的服务类型:', this.serviceTypes);
        } else {
          console.log('获取服务类型失败:', typeRes);
        }
        
        // 3. 默认显示全部服务
        this.switchTab(this.currentTab);
        
      } catch (error) {
        console.error('加载数据失败:', error);
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },


    // 根据服务类型名称生成key
    getTypeKey(typeName) {
      const typeMap = {
        '保养': 'maintain',
        '维修': 'repair', 
        '配件': 'parts',
        '其他': 'other'
      };
      return typeMap[typeName] || typeName.toLowerCase();
    },

    // 获取店铺信息
    getShopInfoById(shopId) {
      return request.get(`/shop/${shopId}`);
    },

    // 获取店铺服务类型列表
    getServiceTypesByShopId(shopId) {
      return request.get(`/serviceDetails/shopServiceTypes/${shopId}`);
    },

    // 根据店铺ID获取所有服务详情（用于"全部"标签）
    getServiceDetailsByShopId(shopId) {
      return request.get(`/serviceDetails/shop/${shopId}`);
    },

    // 根据店铺ID和服务类型ID获取服务详情
    getServiceDetailsByShopAndType(shopId, typeId) {
      return request.get(`/serviceDetails/shop/${shopId}/type/${typeId}`);
    },

    showContactModal() {
      console.log('点击了客服');
      this.isShowContact = true;
    },
    goToNavigation() {
      uni.navigateTo({
        url: `/pages/car_wash/navigation/navigation?longitude=${this.shopInfo.longitude || 113.264535}&latitude=${this.shopInfo.latitude || 23.155477}&name=${this.shopInfo.name || '车百事汽车生活馆'}&address=${this.shopInfo.address || '山阳区人民路与解放路口'}`
      });
    },
    copyPhone() {
      uni.setClipboardData({
        data: this.customerPhone,
        success: () => {
          uni.showToast({ title: "复制成功" });
          this.closeModal();
        }
      });
    },
    makePhoneCall() {
      uni.makePhoneCall({
        phoneNumber: this.customerPhone,
        success: () => {
          this.closeModal();
        }
      });
    },
    closeModal() {
      this.isShowContact = false;
    },
    async switchTab(tabKey) {
      console.log('切换到Tab:', tabKey);
      this.currentTab = tabKey;
      
      try {
        if (tabKey === 'all') {
          // 显示所有服务 - 调用获取所有服务详情的接口
          console.log('调用获取所有服务详情接口，shopId:', this.shopId);
          const res = await this.getServiceDetailsByShopId(this.shopId);
          console.log('获取所有服务详情响应:', res);
          
          if (res.code === 200 && res.data) {
            this.groupBuyList = res.data.map(service => {
              console.log('处理服务数据:', service);
              return {
                id: service.id,
                image: service.img || service.image || '/static/car_wash/group1.png',
                title: service.name || service.title,
                desc: service.introduction || service.desc,
                currentPrice: service.presentPrice || service.currentPrice,
                originalPrice: service.originalPrice,
                tag: service.serviceType ? service.serviceType.name : '其他',
                sales: Math.floor(Math.random() * 100) + 10 // 随机销量
              };
            });
          } else {
            console.log('获取服务详情失败或数据为空:', res);
            this.groupBuyList = [];
          }
        } else {
          // 根据类型筛选服务 - 调用根据类型获取服务详情的接口
          const typeId = this.serviceTypes.find(type => type.key === tabKey)?.typeId;
          console.log('查找类型ID:', tabKey, '找到的typeId:', typeId);
          
          if (typeId) {
            console.log('调用根据类型获取服务详情接口，shopId:', this.shopId, 'typeId:', typeId);
            const res = await this.getServiceDetailsByShopAndType(this.shopId, typeId);
            console.log('根据类型获取服务详情响应:', res);
            
            if (res.code === 200 && res.data) {
              this.groupBuyList = res.data.map(service => {
                console.log('处理分类服务数据:', service);
                return {
                  id: service.id,
                  image: service.img || service.image || '/static/car_wash/group1.png',
                  title: service.name || service.title,
                  desc: service.introduction || service.desc,
                  currentPrice: service.presentPrice || service.currentPrice,
                  originalPrice: service.originalPrice,
                  tag: service.serviceType ? service.serviceType.name : '其他',
                  sales: Math.floor(Math.random() * 100) + 10 // 随机销量
                };
              });
            } else {
              console.log('获取分类服务详情失败或数据为空:', res);
              this.groupBuyList = [];
            }
          } else {
            console.log('未找到对应的服务类型ID');
            this.groupBuyList = [];
          }
        }
        console.log('最终显示的服务列表:', this.groupBuyList);
      } catch (error) {
        console.error('切换标签失败:', error);
        uni.showToast({ title: '加载失败', icon: 'none' });
      }
    },
    selectItem(item) {
      console.log('选择商品:', item);
    },
    buyItem(item) {
      console.log('购买商品:', item);
      // 点击抢购直接跳转到订单详情页面
      uni.navigateTo({
        url: `/pages/car_wash/order_details/order_details?shopId=${this.shopId}&serviceId=${item.id}`
      });
    },
    loadMore() {
      console.log('加载更多');
    }
  }
};
</script>

<style scoped>
/* 页面根容器 */
.page-wrapper {
  position: relative;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.scroll-content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

/* 店铺信息 */
.shop-banner {
  width: 100%;
  height: auto;
}

.shop-info {
  padding: 30rpx;
  background: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
}

.shop-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.shop-rating {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  gap: 15rpx;
}

.stars {
  display: flex;
  gap: 4rpx;
}

.rating-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.sales-text {
  font-size: 26rpx;
  color: #666;
}

.shop-details {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.location-item {
  justify-content: space-between;
  padding: 10rpx 0;
  border-radius: 8rpx;
}

/* 团购区域 */
.group-buy-section {
  margin: 0 20rpx 20rpx;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
}

.tabs {
  display: flex;
  overflow-x: auto;
  padding: 0 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-item {
  font-size: 30rpx;
  white-space: nowrap;
  padding: 25rpx 20rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #ff6600;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: #ff6600;
  border-radius: 2rpx;
}

.group-buy-list {
  padding: 20rpx;
}

.group-buy-item {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.08);
  margin-bottom: 20rpx;
}

.item-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.item-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.3;
}

.item-desc {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
}

.item-price {
  display: flex;
  align-items: baseline;
  gap: 12rpx;
}

.current-price {
  font-size: 36rpx;
  color: #ff4757;
  font-weight: bold;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.item-tags {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.tag {
  font-size: 22rpx;
  color: #fff;
  background: #ff6600;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-weight: 500;
}

.sales {
  font-size: 24rpx;
  color: #999;
}

.buy-btn {
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  color: #fff;
  background: #ff6600;
  border: none;
  border-radius: 30rpx;
  font-size: 26rpx;
  font-weight: 500;
}

.more-group-buy {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 30rpx 0;
  background: #f8f8f8;
  border-radius: 12rpx;
  margin-top: 10rpx;
}

/* 评价部分 */
.review-section {
  margin: 0 20rpx 20rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.review-item {
  display: flex;
  gap: 20rpx;
}

.review-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  flex-shrink: 0;
}

.review-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.review-header {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.review-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.review-stars {
  display: flex;
  gap: 4rpx;
}

.review-date {
  font-size: 24rpx;
  color: #999;
  margin-left: auto;
}

.review-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

/* 底部栏 */
.bottom-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  box-sizing: border-box;
}

.contact-area {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 10rpx 20rpx;
  border-radius: 25rpx;
  background: #f8f8f8;
}

.contact-icon {
  width: 32rpx;
  height: 32rpx;
}

.contact-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

/* 底部弹出层 */
.contact-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9999;
}

.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  box-sizing: border-box;
  transition: transform 0.3s ease;
  transform: translateY(0);
}

.contact-modal[v-show="false"] .modal-content {
  transform: translateY(100%);
}

.phone-number {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  padding: 40rpx 0;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.divider {
  height: 1rpx;
  background-color: #f0f0f0;
}

.copy-btn,
.cancel-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  border: none;
  border-radius: 0;
  font-size: 32rpx;
  text-align: center;
  background-color: #fff;
  color: #333;
}

.cancel-btn {
  background-color: #f8f8f8;
  color: #666;
  border-top: 1rpx solid #f0f0f0;
}
</style>